import type {
  CreateCrudOptionsProps,
  CreateCrudOptionsRet,
} from '@fast-crud/fast-crud';

import { ref } from 'vue';

import { useAccess } from '@vben/access';

import { BaseEmployeeApi } from '#/api';
import { DefUserApi } from '#/api/devOperation/tenant/defUser';
import { DictEnum } from '#/enums/commonEnum';
import { PermCode } from '#/enums/perm';
import { useMessage } from '#/hooks/web/useMessage';
import { $t } from '#/locales';
import {
  backendDict,
  createdTimeColumn,
  indexColumn,
  STATE_CONSTANT_DICT,
  transformQuery,
} from '#/plugins/fast-crud/common';

const { hasPermission } = useAccess();

const permCode = PermCode.devOperation.tenant.defTenant;
export function createCrudOptions(
  props: CreateCrudOptionsProps,
): CreateCrudOptionsRet {
  const selectedRowKeys = ref<string[]>([]);
  const { createConfirm, createMessage } = useMessage();

  return {
    crudOptions: {
      request: {
        pageRequest: DefUserApi.pageUserRequest,
        transformQuery: (query) => {
          const tq = transformQuery(query);
          tq.model.tenantId = props.context.tenantId.value;
          return tq;
        },
      },
      table: {
        striped: true,
        rowKey: 'id',
        rowSelection: {
          type: 'checkbox',
          selectedRowKeys,
          onChange: (changed: string[]) => {
            selectedRowKeys.value = changed;
          },
        },
      },
      actionbar: { buttons: { add: { show: false } } },
      rowHandle: {
        width: 100,
        buttons: {
          view: { show: false },
          edit: { show: false },
          remove: { show: false },
          copy: { show: false },
          unlock: {
            show: hasPermission(permCode.unBind),
            text: '解绑',
            type: 'link',
            click: async (context) => {
              const tenantId = props.context?.tenantId;
              if (!tenantId.value) {
                createMessage.warning('请重新加载页面');
                return;
              }
              const userIdList = [context.row.id];

              if (userIdList && userIdList.length > 0) {
                createConfirm({
                  title: '确认',
                  iconType: 'warning',
                  content: `确定要将此用户与该企业解绑吗`,
                  onOk: async () => {
                    const params = {
                      tenantId: tenantId.value,
                      userIdList,
                      isBind: false,
                    };
                    await BaseEmployeeApi.bindUser(params);
                    createMessage.success('解绑成功');

                    props.crudExpose.doRefresh();
                  },
                });
              } else {
                createMessage.warning('请选择用户');
              }
            },
          },
        },
      },
      columns: {
        ...indexColumn(props.crudExpose),
        username: {
          title: $t('devOperation.tenant.defUser.username'),
          type: 'text',
          search: { show: true },
        },
        email: {
          title: $t('devOperation.tenant.defUser.email'),
          type: 'text',
          search: { show: true },
        },
        mobile: {
          title: $t('devOperation.tenant.defUser.mobile'),
          type: 'text',
          search: { show: true },
        },
        idCard: {
          title: $t('devOperation.tenant.defUser.idCard'),
          type: 'text',
          search: { show: true },
        },
        wxOpenId: {
          title: $t('devOperation.tenant.defUser.wxOpenId'),
          type: 'text',
          form: { show: false },
          column: { show: false },
          viewForm: { show: true },
        },
        ddOpenId: {
          title: $t('devOperation.tenant.defUser.ddOpenId'),
          type: 'text',
          column: { show: false },
          form: { show: false },
          viewForm: { show: true },
        },
        nickName: {
          title: $t('devOperation.tenant.defUser.nickName'),
          type: 'text',
          search: { show: true },
          form: { col: { span: 24 } },
        },
        sex: {
          title: $t('devOperation.tenant.defUser.sex'),
          type: 'dict-radio',
          dict: backendDict(DictEnum.Sex),
        },
        state: {
          title: $t('devOperation.tenant.defUser.state'),
          type: 'dict-radio',
          dict: STATE_CONSTANT_DICT,
          addForm: { value: true },
        },
        workDescribe: {
          title: $t('devOperation.tenant.defUser.workDescribe'),
          type: 'textarea',
          column: { show: false },
          form: { col: { span: 24 } },
        },
        passwordErrorLastTime: {
          title: $t('devOperation.tenant.defUser.passwordErrorLastTime'),
          type: 'password',
          column: { show: false },
          viewForm: { show: true },
          form: {
            show: false,
            component: {
              format: 'yyyy-MM-dd HH:mm:ss',
              valueFormat: 'yyyy-MM-dd HH:mm:ss',
            },
          },
          valueBuilder({ value, row, key }) {
            if (value !== null) {
              row[key] = value;
            }
          },
        },
        passwordErrorNum: {
          title: $t('devOperation.tenant.defUser.passwordErrorNum'),
          type: 'password',
          viewForm: { show: true },
          form: { show: false },
          column: { show: false },
        },
        passwordExpireTime: {
          title: $t('devOperation.tenant.defUser.passwordExpireTime'),
          type: 'password',
          column: { show: false },
          viewForm: { show: true },
          form: {
            show: false,
            component: {
              format: 'yyyy-MM-dd HH:mm:ss',
              valueFormat: 'yyyy-MM-dd HH:mm:ss',
            },
          },
          valueBuilder({ value, row, key }) {
            if (value !== null) {
              row[key] = value;
            }
          },
        },
        lastLoginTime: {
          title: $t('devOperation.tenant.defUser.lastLoginTime'),
          type: 'datetime',
          column: { show: false },
          viewForm: { show: true },
          form: {
            show: false,
            component: {
              format: 'YYYY-MM-DD HH:mm:ss',
              valueFormat: 'YYYY-MM-DD HH:mm:ss',
            },
          },
          valueBuilder({ value, row, key }) {
            if (value !== null) {
              row[key] = value;
            }
          },
        },
        ...createdTimeColumn({}),
      },
    },
  };
}
